<?php

namespace Home\Controller;


class OauthController extends CommonController
{

    public function getCode($url, $returnUrl)
    {
        $theusagt = $_SERVER["HTTP_USER_AGENT"];

        $is_mobile = false;
        if (stripos($theusagt, "iPhone") !== false || stripos($theusagt, "iPod") !== false) {
            $is_mobile = true;
        } else if (stripos($theusagt, "Mac OS") !== false) {
            $is_mobile = false;
        } else if (stripos($theusagt, "Mobile") !== false) {
            $is_mobile = true;
        } else if (stripos($theusagt, "Android") !== false) {
            $is_mobile = false;
        } else if (stripos($theusagt, "Windows Phone") !== false) {
            $is_mobile = true;
        } else {
            $is_mobile = false;
        }

        if ($is_mobile == true) {
            vendor('WxPayPubHelper.WxPayPubHelper');

            $jsApi = new \JsApi_pub();
            //通过code获得openid
            if (!isset($_GET['code'])) {
                //触发微信返回code码
                $url = $jsApi->createOauthUrlForCode('http://oauth.lydlr.com/index.php/Home/Oauth/getOpenId?redirectUrl=' . $url);
                Header("Location: $url");
            }
        } else {
            Header("Location: $returnUrl");
        }
    }


    /**
     * 获得 openID
     */
    public function getOpenId()
    {
        $code = I('get.code');

        if (!empty($code)) {
            //从tencent redirect 来
            vendor('WxPayPubHelper.WxPayPubHelper');
            //使用jsapi接口
            $jsApi = new \JsApi_pub();

            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
        }

        $url = I('get.redirectUrl');
        $url = $url . "?openId=" . $openid;
        Header("Location: $url");
        exit();
    }


}
